using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.Build.Pipeline;
using UnityEditor.Build.Pipeline.Interfaces;
using UnityEngine;
using Directory = UnityEngine.Windows.Directory;

public class MakeAssetBundle
{
    // 资源包输出路径
    private static string BUNDLE_OUTPUT_DIR = Application.dataPath + "/../AssetBundle";
    // 资源包名称定义
    private static string ICON_BUNDLE_NAME = "icon_asset_bundle";
        
    /// <summary>
    /// 打出AssetBundle
    /// </summary>
    [MenuItem("Tools/MakeAssetBundle")]
    public static void Make()
    {
        //创建构建内容
        List<AssetBundleBuild> assetBundleBuilds = new List<AssetBundleBuild>(2);
        assetBundleBuilds.Add(GetOneBundleBuild());
        BundleBuildContent buildContent = new BundleBuildContent(assetBundleBuilds);
        
        // 获取构建参数
        BundleBuildParameters p = GetBuildParameters();
        // 保存构建结果信息
        IBundleBuildResults results;
        
        // 调用接口构建资源包
        ContentPipeline.BuildAssetBundles(p, buildContent, out results);
    }

    private static BundleBuildParameters GetBuildParameters()
    {
        BuildTarget target = BuildTarget.Android;
        BuildTargetGroup group = BuildPipeline.GetBuildTargetGroup(target);

        BundleBuildParameters p = new BundleBuildParameters(target, group, BUNDLE_OUTPUT_DIR);
        p.BundleCompression = BuildCompression.LZ4;
        
        return p;
    }

    private static AssetBundleBuild GetOneBundleBuild()
    {
        // 只测试一个目录，暂时写死
        string assetPath = "Assets/Res/Sprites/icon";

        AssetBundleBuild build = new AssetBundleBuild();

        string[] assetNames = GetAssetNamesFromDir(assetPath);
        
        build.assetBundleName = ICON_BUNDLE_NAME;
        build.assetNames = assetNames;
        build.addressableNames = GetAddressableNames(assetNames);

        return build;
    }

    private static string[] GetAddressableNames(string[] paths)
    {
        List<string> addressableNames = new List<string>();

        for (int i = 0; i < paths.Length; i++)
        {
            addressableNames.Add(Path.GetFileNameWithoutExtension(paths[i]));
        }

        return addressableNames.ToArray();
    }
    private static string[] GetAssetNamesFromDir(string path)
    {
        if (Directory.Exists(path) == false)
        {
            Debug.LogError($"GetAssetNamesFromDir from not exit path : {path}");
            return null;
        }

        string[] assetGuids = AssetDatabase.FindAssets(string.Empty, new[] { path });
        List<string> assetPath = new List<string>(24);
        
        // assetGuid -> assetPath
        for (int i = 0; i < assetGuids.Length; i++)
        {
            assetPath.Add(AssetDatabase.GUIDToAssetPath(assetGuids[i]));
        }

        return assetPath.ToArray();
    }
}
